import 'package:flutter/material.dart';
import 'package:flutter_test_qq/dataBase.dart';
import 'package:flutter_test_qq/mainPage.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'register.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'tencentQQ',
        home: Scaffold(
            body: Login()));
  }
}

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginUI();
}
class LoginUI extends State<Login>{
  bool checkBoxSelected = false;
  bool rememberPwd = false;
  bool isShowPwd = false;
  TextEditingController Name = new TextEditingController(); // qq号
  TextEditingController Pwd = new TextEditingController();
  var qqname = '';// qq昵称
  var qqpic = ''; // qq头像
  save() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("QQ",Name.text.toString());
    prefs.setString("Pwd",Pwd.text.toString());
    prefs.setString("Name",qqname);
    prefs.setString("Done",isShowPwd ==true ?"1":"0");
    prefs.setString('Pic', qqpic);
    print('qqpic:${qqpic}');
  }
 get() async{
   SharedPreferences prefs = await SharedPreferences.getInstance();
   var done = prefs.getString("Done").toString();
   if(done == '1'){
     Name.text = prefs.getString("QQ").toString();
     Pwd.text = prefs.getString("Pwd").toString();
   }
   print('done:${done}');
   print('Name.text:${Name.text}');
   print('Pwd.text:${Pwd.text}');
 }
 @override
  void initState() {
    // TODO: implement initState
    // super.initState();
    get();
    print(111);
  }
  @override
  Widget build(BuildContext context){

    return MaterialApp(
        debugShowCheckedModeBanner: false,
      home: Scaffold(
        body:Column(
            children: [
              const SizedBox(
                child: Image(image: AssetImage("images/logo.jpg"),width:160.0),
                height: 200,
              ),
              SizedBox(
                child:  TextField(
                  controller: Name,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    filled: true,
                    contentPadding: EdgeInsets.all(10.0),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Color(0x00BB0000)),
                      borderRadius: BorderRadius.all(
                        Radius.circular(100),
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Color(0x00000000)),
                      borderRadius: BorderRadius.all(
                        Radius.circular(100),
                      ),
                    ),
                    prefixIcon: Icon(Icons.person),
                    hintText: '请输入QQ号     ',
                  ),
                  autofocus: true,
                  textAlign: TextAlign.right,
                ),
                height: 70,
                width: 300,
              ),
              SizedBox(
                child: (
                    TextField(
                        controller: Pwd,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(10.0),
                          filled: true,
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Color(0x00BB0000)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(100),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Color(0x00000000)),
                            borderRadius: BorderRadius.all(
                              Radius.circular(100),
                            ),
                          ),
                          // labelText: '请输入密码',
                          hintText: '请输入你的密码',
                          prefixIcon: Icon(Icons.lock),
                          suffixIcon: IconButton(
                              onPressed: () {
                                setState(() {
                                  isShowPwd = !isShowPwd;
                                });
                              },
                              icon: Icon(
                                  isShowPwd ? Icons.visibility : Icons.visibility_off )),
                        ),
                        textAlign: TextAlign.right,
                        autofocus: true,
                        obscureText: !isShowPwd
                    )
                ),
                height: 50,
                width: 300,
              ),
              // 记住密码单选框
              Container(
                child: Row(
                  children: [
                    SizedBox(width: 20,),
                    Checkbox(
                      value: rememberPwd,
                      onChanged: (value){
                        setState((){rememberPwd = value!;});
                      },
                    ),
                    Text("记住密码"),
                  ],
                ),
              ),
              // 用户协议单选框
              Container(
                height: 60,
                width: 350,
                child:  Row(
                  children: [
                    SizedBox(width: 15,),
                    Checkbox(
                      value: checkBoxSelected,
                      onChanged: (value){
                        setState((){checkBoxSelected = value!;});
                      },
                    ),
                    // Text("已阅读并同意服务协议和QQ隐私保护指引"),
                    RichText(text: TextSpan(
                        text: '已阅读并同意',
                        style: TextStyle(color: Color(0xFF000000)),
                        children: <TextSpan>[
                          TextSpan(
                            text: '服务协议',
                            style: TextStyle(color: Color(0xFF03A9F4)),
                          ),
                          TextSpan(
                            text:'和',
                            style: TextStyle(color: Color(0xFF000000)),
                          ),
                          TextSpan(
                            text: 'QQ隐私保护指引',
                            style: TextStyle(color: Color(0xFF03A9F4)),
                          )
                        ]
                    ))
                  ],
                ),
              ),
              Container(
                height: 60,
                child: ElevatedButton(
                  onPressed: (){
                    if (checkBoxSelected) {
                      queryDatabase(context);
                    } else {
                      showDialog<Null>(
                          context: context,
                          barrierDismissible: false,
                          builder: (BuildContext context) {
                            return new AlertDialog(
                              // title: new Text('标题'),
                              //可滑动
                              content: new SingleChildScrollView(
                                child: new ListBody(
                                  children: <Widget>[
                                    new Text('请勾选用户协议'),
                                  ],
                                ),
                              ),
                              actions: <Widget>[
                                new ElevatedButton(
                                  child: new Text('确定'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          });
                      print("请勾选协议");
                    }
                  },
                  style: ButtonStyle(
                      shape: MaterialStateProperty.all(const CircleBorder())
                  ),
                  child: const Icon(
                    Icons.arrow_forward,
                    size: 50,
                  ),
                ),
              ),
              Container(
                  height: 100,
                  width: 300,
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('手机号登录'),
                      Text('|'),
                      TextButton(
                        onPressed:(){
                          print('进入注册页面');
                          Navigator.of(context)
                              .push(MaterialPageRoute(builder: (BuildContext context) {
                          return registerPage();

                          }));},
                        child: Text('新用户注册'),
                      ),
                      Text('|'),
                      Text('更多选项'),
                    ],
                  )
              ),
            ],
          )
        )
        // body: MyWidget(),
    );
  }
  queryDatabase(BuildContext context) async {
    TableTestProvider testProvider = TableTestProvider();
    //  通过getDatabasePath()方法获取数据库位置
    var databasePath = await getDatabasesPath();
    String path = join(databasePath, 'demo.db');
    // deleteDatabase(path);
    await testProvider.open(path);
    // 查询数据
    Test qq = await testProvider.getTodo(Name.text);

    setState(() {
      qqname = qq.name as String;
      qqpic = qq.pic as String;
    });
    print('qqname保存：${qqname}');
    print('查询:${qq.toMap()}');
    print('qqid:'+Name.text);
    print('qqpwd:'+Pwd.text);
    if(Name.text!=qq.id||Pwd.text!=qq.pwd){
      print('账号或密码不正确');
      Fluttertoast.showToast(msg: '账号或密码不正确',textColor: Colors.white);
    }
    else{
      Fluttertoast.showToast(msg: '登录成功',textColor: Colors.white);
      save();
      if(rememberPwd == false){
        Pwd.text ='';
      }
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (BuildContext context) {
        return mainPage();
      }));
    }
    // 关闭数据库
    testProvider.close();
  }
}


